<template>
  <!-- 添加|修改SPU的解构 -->
  <el-form>
    <el-form-item label="SPU名称">
      <el-input placeholder="请你输入SPU名称" v-model="spuParams.spuName"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select placeholder="请选择" v-model="spuParams.tmId">
        <el-option :label="item.tmName" :value="item.id" v-for="(item,index) in allTradeMarkArr" :key="item.id">
        </el-option>

      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" v-model="spuParams.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload v-model:file-list="imgListArr" action="/app-dev/admin/product/fileUpload" list-type="picture-card"
        :on-success="handleSuccess" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select v-model="unSaleAttrIdAndName"
        :placeholder="unSelectSaleAttr.length>0?`您还有${unSelectSaleAttr.length}未选择`:`没得选啦`">
        <el-option :label="sale.name" :value="`${sale.id}:${sale.name}`" v-for="(sale,index) in unSelectSaleAttr"
          :key="sale.id"></el-option>

      </el-select>
      <el-button style="margin-left: 10px" type="primary" size="default" :icon="Plus" @click="addSaleAttr">添加销售属性值
      </el-button>
      <el-table border stripe style="margin: 10px 0px" :data="spuHasSaleAttrArr">
        <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
        <el-table-column label="属性名" width="120" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template #="{row,$index}">
            <el-tag style="margin:5px 10px" v-for="(saleValue,index) in row.spuSaleAttrValueList" :key="saleValue.id"
              class="mx-1" closable :type="saleValue.id%2==0?'success':'warning'" :disable-transitions="false"
              @close="row.spuSaleAttrValueList.splice(index,1)">
              {{ saleValue.saleAttrValueName}}
            </el-tag>
            <el-input v-if="row.flag" v-model="row.inputVal" clearable style="width:100px" @blur="toLook(row)">
            </el-input>
            <el-button v-else type="primary" size="small" @click="toEdit(row)"></el-button>


          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #="{row,$index}">
            <el-button type="danger" size="small" :icon="Delete" @click="spuHasSaleAttrArr.splice($index,1)">
            </el-button>
          </template>

        </el-table-column>
      </el-table>

      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage } from 'element-plus'
import { Plus, Delete } from "@element-plus/icons-vue";
//引入请求函数
import { reqAllaTradeMark, reqAllSaleAttr, reqImgList, reqSpuHasSaleAttr, reqAddOrUpdateSpu } from '../../../api/product/spu/spu'
//已有SPU下的全部品牌数据
let allTradeMarkArr = ref([]);
//获取已有SPU下照片墙的数据
let imgListArr = ref([]);
//获取已有SPU，拥有销售属性
let spuHasSaleAttrArr = ref([]);
//获取全部销售属性[不管任何SPU销售属性最多三个]
let allSaleAttrArr = ref([]);

let spuParams = ref({})
//收集SPU还未选择销售属性ID与名字
let unSaleAttrIdAndName = ref('');

const dialogImageUrl = ref("");
//控制对话框显示与隐藏
const dialogVisible = ref(false);

//删除图片回调
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  imgListArr.value = uploadFiles;
};
//预览回调
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
//图片上传成功的回调
const handleSuccess = (response, uploadFile, uploadFiles) => {
  //前两个参数:图片上传成功的信息
  //最后的参数:图片上传成功以后，照片墙全部图片数据
  imgListArr.value = uploadFiles
}
//提供一个方法:将来父组件可以借用的方法
const initHasSpuData = async (spu) => {
  spuParams.value = spu
  //在父组件点击修改SPU按钮的时候，触发子组件当前方法，向服务器发四个请求
  //获取全部品牌数据
  let ps1 = reqAllaTradeMark();
  //获取已有SPU照片墙的数据
  let ps2 = reqImgList(spu.id);
  //获取当前SPU已有销售属性
  let ps3 = reqSpuHasSaleAttr(spu.id);
  //获取全部销售属性
  let ps4 = reqAllSaleAttr();
  //获取全部服务器返回数据
  let result = await Promise.all([ps1, ps2, ps3, ps4]);
  //存储全部品牌
  allTradeMarkArr.value = result[0];
  //存储照片墙的数据 
  imgListArr.value = result[1].map(item => {
    return {
      name: item.imgName,
      url: item.imgUrl
    }
  })
  //存储已有销售属性
  spuHasSaleAttrArr.value = result[2];
  //获取全部销售属性
  allSaleAttrArr.value = result[3];
};
//触发自定义事件
let emit = defineEmits(["changeScene"]);

// 添加属性值按钮
const addSaleAttr = () => {
  // console.log(111);

  const [baseSaleAttrId, saleAttrName] = unSaleAttrIdAndName.value.split(':')
  let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
  // 向spu已有的数组里追加新增的销售属性
  spuHasSaleAttrArr.value.push(newSaleAttr)
  // 清空下拉框的数据
  unSaleAttrIdAndName.value = ''
}
// 剩余属性的数据
const unSelectSaleAttr = computed(() => {
  let result = allSaleAttrArr.value.filter(item => {
    //如果不相等则return出来，为true
    return spuHasSaleAttrArr.value.every(item1 => {
      return item.name != item1.saleAttrName
    })
  })
  return result
})

//添加属性值按钮
const toEdit = (row: any) => {
  row.flag = true
  row.inputVal = ''
}
// input点击事件
const toLook = (row: any) => {
  // 如果为空则清除数据return
  if (row.inputVal.trim() === '') {
    ElMessage({
      type: 'error',
      message: '不能为空'
    })
    return
  }
  // 判断是否与之前数据相等
  let a = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === row.inputVal
  })
  if (a) {
    ElMessage({
      type: 'error',
      message: '不能与之前数据相等'
    })
    //清空最新收集同名属性值
    row.inputValue = '';
    //如果出现同名的属性值显示button
    row.flag = false;
    return
  }
  row.flag = false
  let newSaleattrVal = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.inputVal
  }
  row.spuSaleAttrValueList.push(newSaleattrVal)
  // 清空input
  row.inputVal = ''
}
// 添加回调数据整理
const initAddSpu = async(c3Id: number | string) => {
  spuParams.value.category3Id=c3Id
  // 获取全部品牌数据
  let ps1 = reqAllaTradeMark();
  //  获取全部销售属性的数据
  let ps2 = reqAllSaleAttr();
  let result = await Promise.all([ps1, ps2])
  // 全部商品
  allTradeMarkArr.value = result[0]
  // 全部销售属性
  allSaleAttrArr.value = result[1]
}
// 保存按钮
const save = async () => {
  // 整理参数
  // 照片墙数据
  spuParams.value.spuImageList = imgListArr.value.map(item => {
    return {
      imgUrl: (item.response && item.response.data) || item.url,
      imgName: item.name
    }
  })
  // 属性数据
  spuParams.value.spuSaleAttrList = spuHasSaleAttrArr.value
  try {
    // 发送请求
    await reqAddOrUpdateSpu(spuParams.value)
    ElMessage({
      type: "success",
      message: spuParams.value.id ? "修改成功" : "添加成功",
    });
   
    // 通知父组件
    emit('changeScene', {
      scenes: 0,
      flag: spuParams.value.id ? "update" : "add",
    })
    resetData()
  } catch (error) {
    ElMessage({
      type: "error",
      message: spuParams.value.id ? "修改失败" : "添加失败",
    });
  }
}

// 取消按钮
const cancel=()=>{
  
  emit('changeScene', {
    scenes: 0,
    flag: spuParams.value.id ? "update" : "add",
  })
  resetData()
}
// 清空数据
const resetData = () => {
  spuParams.value = {}
  imgListArr.value = []
  spuHasSaleAttrArr.value = []
}
//对外暴露方法
defineExpose({
  initHasSpuData,
  initAddSpu
});
</script>

<style scoped>

</style>